/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rlpw.swing;

import java.util.ArrayList;
import java.util.List;
import javax.swing.ListSelectionModel;

/**
 *
 * @author weinpau
 */
public class ListSelectModel<T> implements SelectModel<T> {

    private Model<T> model;
    private ListSelectionModel selectionModel;
    private View<T> view;

    public ListSelectModel(Model<T> model, ListSelectionModel selectionModel, View<T> view) {
        this.model = model;
        this.selectionModel = selectionModel;
        this.view = view;
    }

    public Model<T> getDataModel() {
        return model;
    }

    public ListSelectionModel getSelectionModel() {
        return selectionModel;
    }

    public boolean isSelected(int index) {
        return getSelectionModel().isSelectedIndex(index);
    }

    public boolean isSelected(T element) {
        List<T> ls = new ArrayList<T>();
        for (T item : getDataModel()) {
            if (view.getFilter().isVisible(item)) {
                ls.add(item);
            }
        }
        return isSelected(ls.indexOf(element));
    }

    public void setSelected(int index, boolean select) {
        if (select) {
            getSelectionModel().addSelectionInterval(index, index);
        } else {
            getSelectionModel().removeSelectionInterval(index, index);
        }
    }

    public void setSelected(T element, boolean select) {
        setSelected(getDataModel().indexOf(element), select);
    }

    public void setAllSelected(boolean select) {
        if (getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) {
            return;
        } else if (!select) {
            getSelectionModel().clearSelection();
        } else {
            getSelectionModel().setSelectionInterval(0, getDataModel().size() - 1);
        }
    }

    public List<T> getSelected() {
        List<T> result = new ArrayList<T>();
        for (T e : getDataModel()) {
            if (isSelected(e)) {
                result.add(e);
            }
        }
        return result;
    }

    public int countSelected() {
        return getSelected().size();
    }

    public void setMode(int mode) {
        selectionModel.setSelectionMode(mode);
        view.updateView();
    }

    public int getMode() {
        return selectionModel.getSelectionMode();
    }
}
